package com.wmx.zookerper;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * 错误1：Exception in thread "main" org.apache.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /runoob
 * 在每次新建一个节点时，一定要判断该节点（路径）是否存在，因为在ZooKeeper中路径使唯一的，所以当在该路径下已有节点时，继续往当前路径上新建节点就会报这个错。所以删除缓存的version-2文件夹其实就是删除了已经create的节点。
 *
 * 还有一种方式是利用client登录这个zookeeper，然后rmr /节点进行删除节点。
 */
public class ZookerperTest {
    public static void main(String[] args) throws Exception {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("192.168.199.128:2181,192.168.199.129:2181,192.168.199.130:2181", 16000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.getState());
                if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
                    //如果收到了服务端的响应事件，连接成功
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await();
        String s = zooKeeper.create("/runoob2", "吴梦鑫".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(s);
        zooKeeper.close();
        System.out.println(zooKeeper.getState());
    }
}
